import hashlib
import os

import redis
import requests
from flask import Flask, Response, request

app = Flask(__name__)
cache = redis.StrictRedis(host='redis', port=6379, db=0)
salt = 'aaaa'

default_name = 'pan'


@app.route('/', methods=['GET', 'POST'])
def mainpage():
    header = '<html><head><title>Identidock</title></head><body>'
    name = default_name
    if request.method == 'POST':
        name = request.form.get('name', 'xxxxx')
    salted_name = salt + name
    name_hash = hashlib.sha256(salted_name.encode()).hexdigest()

    body = f'''<form method="POST"> Hello <input type="text" name="name" value="{name}"> <input type="submit"> </from>
    <p>You look like a: <img src="/monster/{name_hash}"/></p>
    '''

    env = '<ul>'
    for key, val in dict(os.environ).items():
        env += f"<li><span>{key}</span>  ----  <span>{val}</span></li>"
    env += '</ul>'

    return ''.join([header, body, '<h1> hell world</h1> <hr>', env])


@app.route("/monster/<name>")
def get_identicon(name):
    image = cache.get(name)
    if image is None:
        print('Cache miss', flush=True)
        r = requests.get('http://dnmonster:8080/monster/' + name + '?size=80')
        image = r.content
        cache.set(name, image, ex=60 * 3)
    return Response(image, mimetype='image/png')


if __name__ == '__main__':
    app.run(debug=True, host='0.0.0.0')
